# encoding: utf-8
"""
Tree异常处理系统
"""
import sys

from TVM import TRE
from Compiler import CRE


NameError_ = "NameError"
ValueError_ = "ValueError"
TypeError_ = "TypeError"
SyntaxError_ = "SyntaxError"
VersionError_ = "VersionError"
OpenFileError_ = "OpenfileError"
ModuleNotFoundError_ = "ModuleNotFoundError"
ArgumentError_ = "ArgumentError"
ZeroDivError_ = "ZeroDivError"
RunError_ = "RunError"
AssertError_ = "AssertError"
IndexError_ = "IndexError"
# 函数名与模板字符串相对应，用于在报错时结合传入的报错信息格式化字符串返回
__error = {
    "NameError": 'NameError:name "%s" is not defined.',
    "SyntaxError": "SyntaxError:%s",
    "ValueError": 'ValueError:"%s" could not be "%s"',
    "VersionError": "VersionError:Tree could't run them.Because %s is higher than %s.",
    "OpenFileError": "OpenFileError:could't open '%s'.",
    "ModuleNotFoundError": "ModuleNotFoundError:Tree could't find '%s'.",
    "ArgumentError": "ArgumentError:%s.",
    "ZeroDivError": 'ZeroDivError:"%s" division by zero.',
    "TypeError": "TypeError:%s",
    "RunError": "RunError:%s",
    "AssertError": "AssertError:%s",
    "IndexError": "IndexError:%s is out of %s",
}


def __find(ename: str, args: tuple) -> str:
    """寻找正确的错误类型
    @param ename: 异常名字，用于查找字典
    @param args: 用于格式化字符串的参数
    @return: 一个包含报错信息的字符串
    """
    return f"""
Error from {TRE.TRE_module} 
Error in line {TRE.run_index[TRE.TRE_module]}:
{__error[ename] % args}"""


def send_error(errorname, *args) -> None:
    """报错函数，生成报错字符串并打印，随后停止程序"""
    error_string = __find(errorname, args)
    print(error_string)
    sys.exit()


def __find_compile(ename: str, args: tuple) -> str:
    """寻找正确的错误类型，但仅仅针对编译时期
    @param ename: 异常名字，用于查找字典
    @param args: 用于格式化字符串的参数
    @return: 一个包含报错信息的字符串
    """
    return f"""
Error from {CRE.CRE_module} 
Error in line {CRE.run_index[CRE.CRE_module]}:
{__error[ename] % args}"""


def compile_error(errorname, *args) -> None:
    """报错函数，但仅仅针对编译时期"""
    error_string = __find_compile(errorname, args)
    print(error_string)
    sys.exit()
